<template>
  <div class="workflow-list">
    <page-header
      title="工作流管理"
      description="管理自动化任务的工作流模板，支持多章节、多脚本的复杂任务编排。"
    >
      <el-input v-model="searchQuery" placeholder="搜索工作流..." class="search-input" clearable>
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>
    </page-header>

    <div class="content-wrapper">
      <div class="workflow-grid" v-loading="loading">
        <el-card v-for="workflow in filteredWorkflows" :key="workflow.id" class="workflow-card">
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <h3 class="workflow-name">{{ workflow.name }}</h3>
                <div class="workflow-tags">
                  <el-tag
                    v-for="label in workflow.label"
                    :key="label"
                    size="small"
                    effect="plain"
                    class="tag"
                  >
                    {{ label }}
                  </el-tag>
                </div>
              </div>
              <div class="header-right">
                <el-dropdown
                  trigger="click"
                  @command="handleCommand($event, workflow)"
                  @visible-change="handleDropdownVisibleChange"
                >
                  <el-button type="primary" link>
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu class="workflow-dropdown">
                      <el-dropdown-item command="view">查看详情</el-dropdown-item>
                      <el-dropdown-item command="edit">编辑</el-dropdown-item>
                      <el-dropdown-item command="clone">克隆</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </template>

          <div class="workflow-info">
            <div class="info-item">
              <el-icon><User /></el-icon>
              <span>{{ workflow.author }}</span>
            </div>
            <div class="info-item">
              <el-icon><Calendar /></el-icon>
              <span>{{ formatDateTime(workflow.updateTime) }}</span>
            </div>
            <div class="info-item">
              <el-icon><Collection /></el-icon>
              <span>{{ workflow.chapters.length }} 个章节</span>
            </div>
          </div>

          <div class="workflow-description" v-if="workflow.description">
            {{ workflow.description }}
          </div>

          <div class="workflow-actions">
            <el-button type="primary" @click="router.push(`/task/workflow/${workflow.id}`)">
              <el-icon><View /></el-icon>查看详情
            </el-button>
          </div>
        </el-card>
      </div>

      <!-- 分页 -->
      <div class="pagination">
        <TablePagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[12, 24, 36, 48]"
          :total="total"
          layout="total, sizes, prev, pager, next"
          :teleported="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <floating-action-button tooltip="创建工作流" @click="handleCreate" />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, More, User, Calendar, Collection, View } from '@element-plus/icons-vue'
import type { Workflow } from '@/api/types'
import { taskService } from '@/api/taskService'
import { formatDateTime } from '@/utils/date'
import PageHeader from '@/components/common/PageHeader.vue'
import FloatingActionButton from '@/components/common/FloatingActionButton.vue'
import TablePagination from '@/components/common/TablePagination.vue'

const router = useRouter()
const loading = ref(false)
const workflows = ref<Workflow[]>([])
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const total = ref(0)

// 过滤工作流
const filteredWorkflows = computed(() => {
  const query = searchQuery.value.toLowerCase()
  return workflows.value.filter(
    (workflow) =>
      workflow.name.toLowerCase().includes(query) ||
      workflow.label.some((label) => label.toLowerCase().includes(query)) ||
      workflow.author.toLowerCase().includes(query),
  )
})

// 加载工作流列表
const loadWorkflows = async () => {
  loading.value = true
  try {
    const response = await taskService.getWorkflows({
      page: currentPage.value,
      page_size: pageSize.value,
    })
    workflows.value = response.items
    total.value = response.total
  } catch (err) {
    console.error('获取工作流列表失败:', err)
    ElMessage.error('获取工作流列表失败')
  } finally {
    loading.value = false
  }
}

// 处理分页变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadWorkflows()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadWorkflows()
}

// 处理工作流操作
const handleCommand = async (command: string, workflow: Workflow) => {
  console.log('操作命令:', command)
  console.log('工作流:', workflow)
  switch (command) {
    case 'view':
      router.push(`/task/workflow/${workflow.id}`)
      break
    case 'edit':
      router.push(`/task/workflow/edit/${workflow.id}`)
      break
    case 'clone':
      try {
        await taskService.createWorkflow({
          ...workflow,
          name: `${workflow.name} - 副本`,
          id: undefined,
        })
        ElMessage.success('克隆成功')
        loadWorkflows()
      } catch (err) {
        console.error('克隆工作流失败:', err)
        ElMessage.error('克隆失败')
      }
      break
    case 'delete':
      try {
        await ElMessageBox.confirm(`确认删除工作流 "${workflow.name}"？`, '提示', {
          type: 'warning',
        })
        await taskService.deleteWorkflow(workflow.id)
        ElMessage.success('删除成功')
        loadWorkflows()
      } catch (err) {
        if (err !== 'cancel') {
          console.error('删除工作流失败:', err)
          ElMessage.error('删除失败')
        }
      }
      break
  }
}

// 创建工作流
const handleCreate = () => {
  router.push('/task/workflow/create')
}

// 执行工作流
const handleExecute = (workflow: Workflow) => {
  router.push({
    path: '/task/create',
    query: { workflow: workflow.id },
  })
}

const handleDropdownVisibleChange = (visible: boolean) => {
  console.log('下拉菜单状态:', visible)
  // 检查下拉菜单元素
  const dropdown = document.querySelector('.workflow-dropdown')
  console.log('下拉菜单元素:', dropdown)
}

onMounted(() => {
  loadWorkflows()
})
</script>

<style scoped lang="scss">
.workflow-list {
  position: relative;
  height: 100%;

  .content-wrapper {
    position: relative;
    padding: 24px 24px 56px;
    height: calc(100% - 100px);
    background-color: var(--el-bg-color);
    border-radius: 4px;

    .workflow-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(360px, 1fr));
      gap: 12px;
      margin-bottom: 44px;

      .workflow-card {
        background-color: var(--el-bg-color-overlay);
        transition: all 0.3s ease;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
        }

        :deep(.el-card__header) {
          padding: 10px 14px;
          border-bottom: 1px solid var(--el-border-color-lighter);
        }

        .card-header {
          display: flex;
          justify-content: space-between;
          align-items: flex-start;

          .header-left {
            flex: 1;
            min-width: 0;
            margin-right: 8px;

            .workflow-name {
              margin: 0;
              font-size: 16px;
              font-weight: 500;
              color: var(--el-text-color-primary);
            }

            .workflow-tags {
              margin-top: 6px;
              display: flex;
              flex-wrap: wrap;
              gap: 4px;

              .tag {
                border-radius: 2px;
              }
            }
          }

          .header-right {
            position: relative;
            z-index: 1000;
            .el-button {
              padding: 8px;
              height: 32px;

              .el-icon {
                font-size: 16px;
              }
            }
          }
        }

        .workflow-info {
          margin: 10px 0;
          display: flex;
          flex-wrap: wrap;
          gap: 12px;

          .info-item {
            display: flex;
            align-items: center;
            gap: 4px;
            color: var(--el-text-color-secondary);
            font-size: 13px;

            .el-icon {
              font-size: 14px;
            }
          }
        }

        .workflow-description {
          margin: 10px 0;
          color: var(--el-text-color-regular);
          font-size: 14px;
          line-height: 1.5;
          display: -webkit-box;
          -webkit-box-orient: vertical;
          -webkit-line-clamp: 2;
          overflow: hidden;
        }

        .workflow-actions {
          margin-top: 12px;
          display: flex;
          justify-content: flex-end;
          gap: 8px;

          :deep(.el-button) {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 4px;
            height: 32px;
            line-height: 1;
            padding: 0 16px;

            &.el-button--text {
              color: var(--el-color-primary);
              padding: 0 8px;
              &:hover,
              &:focus {
                color: var(--el-color-primary);
                border-color: transparent;
                background-color: transparent;
              }
            }

            .el-icon {
              margin: 0;
            }

            span {
              line-height: 1;
            }
          }
        }
      }
    }

    .pagination {
      position: absolute;
      bottom: 0;
      left: 0;
      right: 0;
      padding: 12px 24px;
      border-top: 1px solid var(--el-border-color-lighter);
      display: flex;
      justify-content: flex-end;
    }
  }

  .floating-add-button {
    position: fixed;
    right: 70px;
    bottom: 80px;
    width: 56px;
    height: 56px;
    font-size: 24px;
    box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
    transition: all 0.3s ease;

    &:hover {
      transform: scale(1.1);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
    }
  }
}

:deep(.workflow-dropdown) {
  min-width: 120px;
  padding: 4px 0;

  .el-dropdown-menu__item {
    display: flex;
    align-items: center;
    padding: 8px 16px;
    font-size: 14px;
    line-height: 1.5;

    &:hover {
      background-color: var(--el-dropdown-menuItem-hover-fill);
      color: var(--el-dropdown-menuItem-hover-color);
    }

    &.el-dropdown-menu__item--divided {
      border-top-color: var(--el-border-color-lighter);
    }
  }
}

:deep(.el-popper.is-pure) {
  z-index: 3000;
}
</style>
